﻿//------------------------------------------------------------------------------
// <copyright company="Tunynet">
//     Copyright (c) Tunynet Inc.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System.Collections.Generic;
using System.Linq;

namespace Tunynet.Common
{
    public static class IEnumerableExtensions
    {
        /// <summary>
        /// 集合列表转换成分页列表
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="source">源文件</param>
        /// <param name="pageSize">页个数</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="totalRecords">总条数，默认不传，如果已经分好页则必须传</param>
        /// <returns>分页列表</returns>
        public static PagingDataSet<TSource> ConvertToPagingDataSet<TSource>(this IEnumerable<TSource> source, int pageSize, int pageIndex, long? totalRecords = null)
        {
            IEnumerable<TSource> sources = null;
            long count = 0;
            if (!totalRecords.HasValue)
            {
                sources = source.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                count = source.Count();
            }
            else
                count = totalRecords.Value;
            var tDestinations = new PagingDataSet<TSource>(sources)
            {
                TotalRecords = count,
                PageSize = pageSize,
                PageIndex = pageIndex
            };
            return tDestinations;
        }
    }
}